package com.huiyou.base;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huiyou.config.Config;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huiyou.base.BaseMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * conditon 加上noD      不装饰
 */

@Service
public abstract class BaseService<D extends BaseModel, M extends BaseMapper<D>> implements changeModelInterface<D> {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    protected M mapper;

    @Override
    public D change(D model, Map condition) {
        return model;
    }

    private D beforeChange(D model, Map condition) {
        if (model == null) {
            return null;
        }
        if (condition == null) {
            return model;
        }
        if (condition.get("noD") != null) { //不装饰
            return model;
        }
        return change(model, condition);
    }

    public PageInfo<D> getList(Map condition, int page, int pageSize) {

        PageHelper.startPage(page, pageSize);
        List<D> models = mapper.getList(condition);
        PageInfo<D> p = new PageInfo<>(models);

        List<D> stream = models.stream().map(model -> {
            return beforeChange(model, condition);
        }).collect(Collectors.toList());
        p.setList(stream);
        return p;
    }


    public PageInfo<D> getList(Map condition, int page) {
        return this.getList(condition, page, Config.PageSize);
    }


    public List<D> getList(Map condition) {
        List<D> list = mapper.getList(condition);
        List<D> stream = list.stream().map(model -> beforeChange(model, condition)).collect(Collectors.toList());
        return stream;

    }

    public List<D> getListLite(Map condition) {
        List<D> list = mapper.getList(condition);
        return list;

    }

    public D getById(Integer id) {
        if (id == null) {
            return null;
        }
        D model = mapper.getById(id);
        return model;
    }

    public D getById(Integer id, Map condition) {
        D model = this.getById(id);
        if (model == null) {
            return null;
        }
        return beforeChange(model, condition);
    }

    public Integer getCount(Map condition) {
        return mapper.getCount(condition);
    }

    public boolean update(D model) {
        return mapper.update(model) > 0 ? true : false;
    }

    public boolean create(D model) {

        return mapper.create(model) > 0 ? true : false;
    }


    public Integer delete(Map condition) {
        return mapper.delete(condition);
    }

    public boolean deleteById(Integer id) {
        return mapper.deleteById(id) > 0 ? true : false;
    }
}
